import { defineStore } from 'pinia'
import { ref,computed  } from 'vue'
import { login, logout, getUserInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'

export const useUserStore = defineStore('user', () => {
    const token = ref(getToken())
    const name = ref('')
    const nickname = ref('')
    const avatar = ref('')
    const email = ref('')
    const roles = ref([])

    const hasUserInfo = computed(() => {
        return name.value && roles.value.length > 0
    })

    // 登录
    async function userLogin(loginForm) {
        try {
            const { data } = await login(loginForm)
            setToken(data.token)
            token.value = data.token
        } catch (error) {
            removeToken()
            throw error
        }
    }

    // 获取用户信息
    async function fetchUserInfo() {
        try {
            const { data } = await getUserInfo()
            name.value = data.username
            nickname.value = data.nickname
            avatar.value = data.avatar
            email.value = data.email
            roles.value = data.roles
        } catch (error) {
            removeToken()
            throw error
        }
    }

    // 退出登录
    async function userLogout() {
        try {
            await logout()
        } finally {
            resetState()
        }
    }

    // 重置状态
    function resetState() {
        token.value = ''
        name.value = ''
        avatar.value = ''
        roles.value = []
        removeToken()
    }

    return {
        token,
        name,
        nickname,
        avatar,
        email,
        roles,
        hasUserInfo,
        login: userLogin,
        getUserInfo: fetchUserInfo,
        logout: userLogout
    }
})
